<template>
  <view class="chat-container">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="navbar-content">
        <view class="navbar-left" @click="goBack">
          <u-icon name="arrow-left" size="40" color="#333"></u-icon>
        </view>
        <view class="navbar-title">{{ dfName }}</view>
        <view class="navbar-right" @click="showMore">
          <u-icon name="more-dot-fill" size="20" color="#333"></u-icon>
        </view>
      </view>
    </view>
    <!--    占位-->
    <view style="width: 100rpx;height: 200rpx;"></view>
    <!-- 消息列表区域 -->
    <scroll-view
        class="message-list"
        scroll-y
        :scroll-top="scrollTop"
        scroll-with-animation
        @scrolltoupper="loadMoreMessages"
    >
      <view class="message-item" v-for="(message, index) in messageList" :key="index">
        <!-- 对方消息 - 靠左侧 -->
        <view class="message-left" v-if="!message.isMe">
          <view class="message-bubble left-bubble">
            <text class="message-text">{{ message.content }}</text>
            <view class="message-time">
              <text class="time-text">{{ message.time }}</text>
              <text class="read-status" v-if="message.readStatus">{{ message.readStatus }}</text>
            </view>
          </view>
        </view>

        <!-- 自己发送的消息 - 靠右侧 -->
        <view class="message-right" v-else>
          <view class="message-bubble right-bubble">
            <text class="message-text">{{ message.content }}</text>
            <view class="message-time">
              <text class="time-text">{{ message.time }}</text>
              <text class="read-status" v-if="message.readStatus">{{ message.readStatus }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 加载更多提示 -->
      <view class="load-more" v-if="hasMore">
        <u-loading-icon mode="circle" size="16"></u-loading-icon>
        <text class="load-text">加载更多消息...</text>
      </view>
    </scroll-view>

    <!-- 底部输入区域 -->
    <view class="input-container">
      <view class="input-box">
        <textarea
            class="message-input"
            v-model="inputMessage"
            placeholder="请输入内容..."
            :maxlength="500"
            :auto-height="true"
            :show-confirm-bar="false"
            @focus="onInputFocus"
            @blur="onInputBlur"
        ></textarea>
        <view class="send-btn" @click="sendMessage" :class="{ active: inputMessage.trim() }">
          <text class="send-text">发送</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import {
  mapGetters
} from 'vuex'

export default {
  data() {
    return {
      statusBarHeight: 0,
      scrollTop: 0,
      inputMessage: '',
      hasMore: false,
      dfOpenId: "",//对方openId
      dfCardId: "",//对方cardId
      dfName: "",//对方的名字
      shopId: "",//消息中的店铺id(自己或对方的)
      shopInfo: {},//店铺信息
      realeMessageList: [],//这是真实的聊天记录,作为传参数使用
      messageList: [
        // {
        //   id: 1,
        //   content: '你好，请问这个产品还有货吗？',
        //   time: '09:19',
        //   isMe: false,
        //   readStatus: '已读'
        // },
      ]
    }
  },

  onLoad(options) {
    this.dfCardId = options.cardId || ''
    this.dfOpenId = options.openId || ''
    this.dfName = options.name || '消息详情'
    this.shopId = options.shopId || ''
    if (this.shopId) {
      this._getShopInfo()
    }
    this.getSystemInfo()
    // this.loadContactInfo(options)
    this.loadMessages()
    // 延迟滚动到底部
    setTimeout(() => {
      this.scrollToBottom()
    }, 100)
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  methods: {
    // 获取系统信息
    getSystemInfo() {
      const systemInfo = uni.getSystemInfoSync()
      this.statusBarHeight = systemInfo.statusBarHeight || 0
    },

    // // 加载联系人信息
    // loadContactInfo(options) {
    //   if (options.name) {
    //     this.contactInfo.name = decodeURIComponent(options.name)
    //   }
    //   if (options.source) {
    //     this.contactInfo.source = decodeURIComponent(options.source)
    //   }
    // },

    // 加载消息列表
    loadMessages() {
      //   获取与商家沟通记录
      let params = {
        pageNo: 1,
        pageSize: 500,
        cardId: this.userInfo.id,//自己cardId
        // openId:this.userInfo.openId,//自己openId
        operatorCardId: this.dfCardId,//对方cardId
        // operatorOpenId: this.dfOpenId,//对方openId
      }
      this.$api.getMssdShopRecords(params).then(res => {
        if (res.success) {
          if (res.result.records.length > 0) {
            this.realeMessageList = JSON.parse(JSON.stringify(res.result.records))
            this.messageList = (res.result.records || []).map(msg => ({
              id: msg.id,
              content: msg.info,
              time: msg.createTime ? msg.createTime : '',
              isMe: msg.cardId === this.userInfo.id,
              readStatus: msg.status === 1 ? '已读' : '未读'
            }))
          } else {
            this.realeMessageList = []
            this.messageList = []
          }

        }
        console.log('沟通记录', this.messageList)
      })
    },

    // 加载更多消息
    loadMoreMessages() {
      if (this.hasMore) {
        console.log('加载更多消息')
        // 这里可以调用API加载更多消息
      }
    },
    // 根据id获取店铺聊天中涉及的的信息
    _getShopInfo() {
      let params = {
        id: this.shopId
      }
      this.$api.getMssdShopDetail(params).then(res => {
        if (res.success) {
          this.shopInfo = res.result
          console.log('店铺信息', res)
        }
      })
    },
    // 发送消息
    sendMessage() {
      console.log('自己个人信息', this.userInfo)
      if (!this.inputMessage.trim()) {
        uni.showToast({
          title: '请输入消息内容',
          icon: 'none'
        })
        return
      }
      let newMessage = {}
      if (this.realeMessageList.length > 0) {
        //   说明有历史记录,需要取最后一条的信息内容/判断是不是我自己发的
        let lastMessage = this.realeMessageList[this.realeMessageList.length - 1]
        console.log('最后一条消息', lastMessage)
        // 判断是不是自己发送的最后一条
        if (lastMessage.cardId === this.userInfo.id) {
          // 继续使用上条消息的基本信息
          newMessage.cardId = lastMessage.cardId//自己cardId
          newMessage.openId = lastMessage.openId//自己openId
          newMessage.operatorCardId = lastMessage.operatorCardId//对方cardId
          newMessage.operatorOpenId = lastMessage.operatorOpenId//对方openId
          newMessage.company = this.shopId //店铺id
          newMessage.head = lastMessage.head //自己头像
          newMessage.name = lastMessage.name //自己名字
          newMessage.info = this.inputMessage.trim() //发送的内容
          newMessage.operatorHead = lastMessage.operatorHead || '' //接受者头像
          newMessage.operatorName = lastMessage.operatorName || '' //接受者名字
        } else {
          // 基本信息互换
          newMessage.cardId = lastMessage.operatorCardId//自己cardId
          newMessage.openId = lastMessage.operatorOpenId//自己openId
          newMessage.operatorCardId = lastMessage.cardId//对方cardId
          newMessage.operatorOpenId = lastMessage.openId//对方openId
          newMessage.company = this.shopId //店铺id
          newMessage.head = lastMessage.operatorHead //自己头像
          newMessage.name = lastMessage.operatorName //自己名字
          newMessage.info = this.inputMessage.trim() //发送的内容
          newMessage.operatorHead = lastMessage.head || '' //接受者头像
          newMessage.operatorName = lastMessage.name || '' //接受者名字
        }
      } else {
        //   如果没有聊天记录的话,说明我是普通用户
        newMessage.cardId = this.userInfo.id//自己cardId
        newMessage.openId = this.userInfo.openId//自己openId
        newMessage.operatorCardId = this.dfCardId//对方cardId
        newMessage.operatorOpenId = this.dfOpenId//对方openId
        newMessage.company = this.shopId //店铺id
        newMessage.head = this.userInfo.head //自己头像
        newMessage.name = this.userInfo.name //自己名字
        newMessage.info = this.inputMessage.trim() //发送的内容
        newMessage.operatorHead = this.shopInfo.shopLogo || '' //接受者头像
        newMessage.operatorName = this.shopInfo.shopName || '' //接受者名字
      }


      const showMessage = {
        id: Date.now(),
        content: this.inputMessage.trim(),
        time: this.getCurrentDate(),
        isMe: true,
        readStatus: '未读',
      }

      this.messageList.push(showMessage)
      this.inputMessage = ''

      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom()
      })

      // 这里可以调用API发送消息
      console.log('发送消息:', newMessage)
      this.$api.sendMssdShopMessage(newMessage).then(res => {
        if (res.success) {
          this.loadMessages()
        } else {
          uni.showToast({
            title: `发送失败，请稍后重试`,
            icon: 'none'
          })
        }
      })
    },

    // 获取当前时间
    getCurrentTime() {
      const now = new Date()
      const hours = now.getHours().toString().padStart(2, '0')
      const minutes = now.getMinutes().toString().padStart(2, '0')
      return `${hours}:${minutes}`
    },
    // 获取当前日期
    getCurrentDate() {
      const now = new Date()
      const year = now.getFullYear()
      const month = (now.getMonth() + 1).toString().padStart(2, '0')
      const day = now.getDate().toString().padStart(2, '0')
      return `${year}-${month}-${day}`
    },

    // 滚动到底部
    scrollToBottom() {
      this.scrollTop = 99999
    },

    // 输入框获得焦点
    onInputFocus() {
      setTimeout(() => {
        this.scrollToBottom()
      }, 300)
    },

    // 输入框失去焦点
    onInputBlur() {
      // 可以在这里处理键盘收起后的逻辑
    },

    // 返回上一页
    goBack() {
      uni.navigateBack()
    },

    // 显示更多选项
    showMore() {
      uni.showActionSheet({
        itemList: ['查看资料', '清空聊天记录'],
        success: (res) => {
          if (res.tapIndex === 0) {
            // 查看资料
            console.log('查看资料')
          } else if (res.tapIndex === 1) {
            // 清空聊天记录
            this.clearMessages()
          }
        }
      })
    },

    // 清空聊天记录
    clearMessages() {
      uni.showModal({
        title: '提示',
        content: '确定要清空聊天记录吗？',
        success: (res) => {
          if (res.confirm) {
            this.messageList = []
            console.log('清空聊天记录')
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.chat-container {
  height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
  position: relative;
}

.custom-navbar {
  background-color: #fff;
  border-bottom: 2rpx solid #eee;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  flex-shrink: 0;
}

.navbar-content {
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30rpx;
}

.navbar-left {
  width: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;

  .u-icon__icon {
    font-weight: bold !important;
  }
}

.navbar-title {
  flex: 1;
  text-align: center;
  font-size: 36rpx;
  font-weight: 500;
  color: #333;
}

.navbar-right {
  width: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.message-list {
  flex: 1;
  height: 0;
  /* margin-top: 88rpx ; */
  /* padding: 30rpx ; */
  padding-bottom: 264rpx;
  background-color: #f5f5f5;
}

.message-item {
  margin-bottom: 30rpx;
  display: flex;
  padding: 0 30rpx;
  //padding: 20rpx 30rpx;
}

.message-left {
  justify-content: flex-start;
  width: 100%;
}

.message-right {
  justify-content: flex-end;
  width: 100%;
}

.message-bubble {
  max-width: 70%;
  padding: 20rpx 30rpx;
  border-radius: 16rpx;
  position: relative;
}

.left-bubble {
  background-color: #fff;
  border: 2rpx solid #e5e5e5;
  border-radius: 16rpx 16rpx 16rpx 4rpx;
  margin-right: auto;
  margin-left: 0;

  .message-time {
    .time-text {
      font-size: 24rpx;
      color: #a7a7a7 !important;
    }
  }
}

.right-bubble {
  background-color: #4182bb;
  border-radius: 16rpx 16rpx 4rpx 16rpx;
  margin-left: auto;
  margin-right: 0;

  .message-text {
    color: #fff !important;
  }

  .message-time {
    color: rgba(255, 255, 255, 0.8) !important;
  }
}

.message-text {
  font-size: 32rpx;
  line-height: 1.4;
  color: #333;
  word-wrap: break-word;
}

.message-time {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.8);
  margin-top: 10rpx;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 10rpx;
}

.time-text {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.8);
}

.read-status {
  font-size: 22rpx;
  color: #1abd69;
  font-weight: 500;
}

.load-more {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx;
  color: #999;
}

.load-text {
  font-size: 24rpx;
  margin-left: 10rpx;
}

.input-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  border-top: 2rpx solid #e5e5e5;
  padding: 30rpx;
  padding-bottom: calc(30rpx + env(safe-area-inset-bottom));
  flex-shrink: 0;
  box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.input-box {
  display: flex;
  align-items: flex-end;
  background-color: #f8f8f8;
  border-radius: 50rpx;
  padding: 20rpx 30rpx;
  min-height: 80rpx;
  border: 2rpx solid #e8e8e8;
  transition: all 0.3s ease;
}

.message-input {
  flex: 1;
  font-size: 32rpx;
  line-height: 1.4;
  color: #333;
  background-color: transparent;
  border: none;
  outline: none;
  max-height: 200rpx;
  min-height: 48rpx;
}

.send-btn {
  margin-left: 24rpx;
  padding: 14rpx 36rpx;
  background-color: #d0d0d0;
  border-radius: 40rpx;
  transition: all 0.3s ease;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;

  &.active {
    background-color: #4182bb;
    box-shadow: 0 4rpx 12rpx rgba(65, 130, 187, 0.3);
    transform: translateY(-2rpx);
  }
}

.send-text {
  font-size: 28rpx;
  color: #fff;
  font-weight: 600;
}

/* 输入框聚焦状态 */
.input-box:focus-within {
  background-color: #fff;
  border: 2rpx solid #4182bb;
  box-shadow: 0 0 0 4rpx rgba(65, 130, 187, 0.1);
}
</style>
